package hzk.codex2016.list;

public class LinkedList_CRUD {

	public ListNode get(ListNode head,int index){
		while (head!=null && index-->0) head=head.next;
		return head;
	}
	public ListNode insert(ListNode head,ListNode e,int pos){
		if (pos==0 || head==null){
			e.next=head;
			return e;
		}
		ListNode pre=head,p=head.next;
		while (pos-->0 && p!=null){
			pre=p;
			p=p.next;	
		}
		//insert e between pre and p
		pre.next=e;
		e.next=p;
		return head;
		
	}
	
	/**
	 * https://leetcode.com/problems/delete-node-in-a-linked-list/
	 * @param node
	 */
    public void deleteNode(ListNode node) {
    	if (node==null || node.next==null) return;
    	ListNode pre=node,p=node.next;
    	while (p.next!=null){
    		pre.val=p.val;
    		
    		pre=p;
    		p=p.next;
    	}
    	pre.val=p.val;
    	pre.next=null;
    	
    	
    }
	
	
	public static void main(String[] args){
		LinkedList_CRUD s=new LinkedList_CRUD();
	
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),0));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),1));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),2));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),3));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),4));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),5));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),6));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),8));
		System.out.println(s.insert(Lists.sll(1,2,3,4,5,6),new ListNode(99),8));
		
		ListNode a=Lists.sll(1,2,3,4,5,6);
		s.deleteNode(s.get(a, 0));
		System.out.println(a);
	}
}
